package com.xxadmin.usercenter.config.security.handler;

import com.xxadmin.common.exception.BusinessException;
import com.xxadmin.common.exception.errorcode.ErrorCode;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

@Component("customWebResponseExceptionTranslator")
public class CustomWebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator {
    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {

        ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);

        CustomOauthException exception = null;
        // 业务类异常
        if(e instanceof BusinessException){
            BusinessException be = (BusinessException) e;

            exception = new CustomOauthException(be.getErrorCode(),((BusinessException) e).getErrorMessage());
        }else{
            // 系统异常
            exception = new CustomOauthException(ErrorCode.OAUTH2_ERRRO,e.getMessage());
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setAll(responseEntity.getHeaders().toSingleValueMap());

        return new ResponseEntity<>(exception, headers, responseEntity.getStatusCode());
    }
}
